package edu.luas.digitalmedia.controller;

import edu.luas.digitalmedia.pojo.User;
import edu.luas.digitalmedia.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/insert")
public class UserInsertController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1:设置请求编码
        req.setCharacterEncoding("utf-8");
        //2:设置响应编码
        resp.setContentType("text/html;charset=utf-8");
        //3:获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");


        User model = new User();
        model.setUsername(username);
        model.setPassword(password);


        //4:调用业务方法处理请求
        try {
            int count = new UserService().insert(model);
            if (count>0){
                resp.getWriter().print("添加成功");
            }else {
                resp.getWriter().print("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().print("添加失败");
        }
        //5:控制页面跳转
        req.getRequestDispatcher("/login.jsp").forward(req,resp);
    }
}
